package com.party.mem.biz.file;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.service.picCloud.CosCloudBizService;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import com.party.mem.utils.excel.ExportExcel;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: Excel导出
 * @Date:Created in 2017/10/18 0018 上午 10:16.
 */
@Service
public class ExcelExportService {

    private String uploadPath = Constant.UPLOAD_EXCEL;

    @Autowired
    private StringJedis stringJedis;

    private static final String REDIS_LIST_KEY = "export_excel_list";

    @Autowired
    private CosCloudBizService cosCloudBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 上传excel
     *
     * @param fileName    文件名
     * @param exportPath  目录
     * @param exportExcel 文件
     * @return
     */
    public synchronized String getExcelPath(String fileName, String exportPath, ExportExcel exportExcel) throws IOException {
        String suffix = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
        if (fileName.indexOf(".xlsx") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xlsx")) + '-' + suffix + ".xlsx";
        } else if (fileName.indexOf(".xls") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xls")) + '-' + suffix + ".xls";
        }
        try {
            exportPath = String.format(uploadPath, exportPath, fileName);
            InputStream inputStream = exportExcel.newUploadCloud();
            UploadResult uploadResult = cosCloudBizService.uploadFile(inputStream, exportPath, InsertOnly.NO_OVER_WRITE);
            String resourceUrl = uploadResult.getSourceUrl();
            pushRedis(resourceUrl);
            return resourceUrl;
        } catch (Exception e) {
            logger.error("上传Excel到腾讯云异常：cloudFilePath——" + exportPath + "；cloudFileName——" + fileName, e);
        }
        return null;
    }

    /**
     * 上传excel
     *
     * @param fileName    文件名
     * @param exportPath  目录
     * @param exportExcel 文件
     * @param wb          文件
     * @return
     */
    public synchronized String getExcelPath(String fileName, String exportPath, ExportExcel exportExcel, SXSSFWorkbook wb) throws IOException {
        exportExcel.setWb(wb);
        return getExcelPath(fileName, exportPath, exportExcel);
    }

    public List<Map> getRedisAll() {
        List<Map> mapList = Lists.newArrayList();
        String result = stringJedis.getValue(REDIS_LIST_KEY);
        if (StringUtils.isNotEmpty(result)) {
            mapList = JSONArray.parseArray(result, Map.class);
        }
        return mapList;
    }

    public void pushRedis(String resourceUrl) {
        try {
            resourceUrl = URLDecoder.decode(resourceUrl, Constant.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<Map> mapList = getRedisAll();
        Map<String, Object> map = Maps.newHashMap();
        map.put(resourceUrl, DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN));
        mapList.add(map);
        stringJedis.setValue(REDIS_LIST_KEY, JSONObject.toJSONString(mapList));
    }
}
